package stream;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class StreamDemo {
	//主要操作集合,!!!从流里读取完的元素，就不存在流中了
	List<String> list;
	Stream<String> stream;
	
	@BeforeEach
	public void init() { 
		list = new ArrayList<>();
		Collections.addAll(list, "lasjsaf","hellokitty","abcd","hello","howareyou","kaoniqiwa","abcd","aaa");
		//线程不安全的流
		stream = list.stream();
		//线程安全的并发流
		//Stream<String> parallelStream = list.parallelStream();
	}
	
	@Test
	public void func1() {  
		// [].length  "abc".length()   list.size()  set.size()  map.size()  stream.count()
		
		// 如果一个流使用完毕，就不能再被使用
		//long count = stream.count();
		//System.out.println("流元素个数:" + count);
		
		// 排序后stream里没有元素，排序后产生新流
		//Stream<String> s = stream.sorted();
		//s.forEach(System.out::println);                        // Consumer -> void accept(T t);
		
		List<String> copy = new ArrayList<>();
		stream.forEach(copy::add);  // 对象::非静态方法
		copy.forEach(System.out::println);
	}
	
	@Test
	public void func2() {
		//   类名::非静态方法
//		Stream<String> map = stream.map(String::toUpperCase);   //  Function -> R apply(T)  t.toUpperCase()
//		map.forEach(System.out::println);
		
		//map要给每个元素进行处理，返回处理后的元素
//		Stream<String> map = stream.map(t->t.substring(0,4));
//		map.forEach(System.out::println);
		
		//把每个字符串中的a去掉 replace  lambda
		Stream<String> map2 = stream.map(t->t.replace("a",""));
		map2.forEach(System.out::println);
	}
	
	@Test
	public void func3() {
		// 过滤流中的每个元素，断言的条件如果为真才放入新流。
//		Stream<String> s = stream.filter(t->t.length()>6); // Predicate  boolean test(T)
//		s.forEach(System.out::println);
		
//		Stream<String> s2 = stream.filter(String::isEmpty); // 类名::非静态方法
//		System.out.println(s2.count());
		
		Stream<String> s3 = stream.filter(t->t.contains("ab")); 
		s3.forEach(System.out::println);
	}
	
	@Test
	public void func4() {
		// distinct 去重复，相同只留一份
		Stream<String> s1 = list.stream().distinct();
		s1.forEach(System.out::println);
		System.out.println("-----------------------------");
		// 只流前几个
		Stream<String> s2 = list.stream().limit(3);
		s2.forEach(System.out::println);
		System.out.println("-----------------------------");
		// 从第三个开始，越过前两个元素
		Stream<String> s3 = list.stream().skip(2);
		s3.forEach(System.out::println);
		System.out.println("-----------------------------");
		
		Stream<String> s4 = list.stream().distinct().
				filter(t->t.length()>6).map(String::toUpperCase).sorted();
		s4.forEach(System.out::println);
		System.out.println("-----------------------------");
	}
}








